package com.scorekeeper;

import java.util.Calendar;
import java.util.Date;

import com.scorekeeper.utils.DBProvider;
import com.scorekeeper.utils.DBProvider.Table;
import com.scorekeeper.utils.Logger;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class Main extends Activity {
	public static Context ctx = null;
	static final int REFRESH_STANDINGS = 1;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ctx = this.getApplicationContext();
        
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        
        Calendar cal =  Calendar.getInstance();
        Date lastUpdated = new DBProvider().lastUpdateDate(Table.TEAM);
        if (lastUpdated != null) {
	        cal.setTime(lastUpdated);
	        cal.add(Calendar.DATE, 2);
	        if (Calendar.getInstance().after(cal)) {
	        	//do an update
	        	
	        }
        }
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.main_menu, menu);
			return true;
		} catch (Exception e) {
			Logger.LogError(e);
			return false;
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent myIntent = null;
		
		try {
			switch (item.getItemId()) {
			case R.id.refresh_standings:
				FragmentTransaction ft = getFragmentManager().beginTransaction();
				Fragment prev = getFragmentManager().findFragmentByTag("load_standings");
				if (prev != null) {
					ft.remove(prev);
				}
				ft.addToBackStack(null);
				
				// Create the fragment.
				Fragment newFragment = RefreshStandings.newInstance();
				ft.add(newFragment, "load_standings");
				ft.commit();
				
				buildTeamRows();
				return true;
			case R.id.view_standings:
				myIntent = new Intent()
					.setClassName("com.scorekeeper", "com.scorekeeper.ui.LeagueStandings");
				startActivity(myIntent);
                
				return true;
			case R.id.close:
				this.finish();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		} catch (Exception e) {
			Logger.LogError(e);
			return false;
		} 
	}
	
	private void buildTeamRows() {
		
	}
}